package com.tql.pandian.util;

import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.io.UnsupportedEncodingException;

/**
 * 汉语拼音工具类
 *
 * @author zhengcl
 * @date 2023-10-16
 */
@Slf4j
public class PinYinUtil {

    static HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();

    static {
        outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        outputFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
    }

    public static String getPinyin(String name) {
        try {
            name = PinyinHelper.toHanYuPinyinString(name, outputFormat, "", true);
        }catch (BadHanyuPinyinOutputFormatCombination e) {
            log.error(e.getMessage());
        }
        return name;
    }

    public static String getHeadPinyin(String name) {
        StringBuilder sb = new StringBuilder();
        try {
            char[] aa = name.toCharArray();
            for (char b : aa) {
                String[] strings = PinyinHelper.toHanyuPinyinStringArray(b, outputFormat);
                for (String d : strings) {
                    char ccc = d.charAt(0);
                    sb.append(ccc);
                }
            }
        }catch (BadHanyuPinyinOutputFormatCombination e) {
            log.error(e.getMessage());
        }
        return sb.toString();
    }

    public static char getChineseFirstLetter(String str){
        if (str == null || str.isEmpty()){
            return ' ';
        }else {
            int highByte;
            try {
                byte[] bytes = str.getBytes("GBK"); // 根据系统默认编码选择合适的编码格式
                for (int i = 0; i < bytes.length; i++){
                    highByte = ((bytes[i] & 0xFF) >> 4); // 提取高位字节
                    if (highByte >= 17 && highByte <= 23) { // 范围内表示汉字
                        return (char)(bytes[i] & 0xFF); // 返回当前字节作为首字母
                    }
                }
            }catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return ' ';
    }

}
